import 'package:dio/dio.dart';
import 'package:zhaoxiaowu_app/models/user.dart';
import 'package:zhaoxiaowu_app/utils/utils.dart';

class Global {
  static Global? _instance;

  Dio _dio = Dio();

  String token = "";
  User? user;

  static Global shared() {
    return _instance ??= Global();
  }

  Global() {
    _dio.options = BaseOptions(
      baseUrl: "https://zxw.td0f7.cn",
      connectTimeout: 5000,
      sendTimeout: 5000,
      receiveTimeout: 5000,
      headers: {
        "token": "132311",
      },
      contentType: Headers.formUrlEncodedContentType,
      responseType: ResponseType.json,
    );
    _dio.interceptors.add(InterceptorsWrapper(
      onResponse: (response, handler) {
        ToastUtils.dismissActivity();
        return handler.next(response);
      },
      onError: (e, handler) {
        print("错误" + e.type.toString());
        ToastUtils.dismissActivity();
        String msg;
        switch (e.type) {
          case DioErrorType.connectTimeout:
            msg = "连接超时错误";
            break;
          default:
            msg = "网络错误";
            break;
        }
        ToastUtils.showError(msg);
      },
    ));
  }

  Future<Response<T>> post<T>(String path, {Map<String, dynamic>? parameters, dynamic data}) async {
    return _dio.post(path, queryParameters: parameters, data: data);
  }

  Future<Response<T>> get<T>(String path, {Map<String, dynamic>? parameters}) async {
    return _dio.get(path, queryParameters: parameters);
  }

  Future<Response<T>> put<T>(String path, {Map<String, dynamic>? parameters}) async {
    return _dio.put(path, queryParameters: parameters);
  }

  Future<Response<T>> delete<T>(String path, {Map<String, dynamic>? parameters}) async {
    return _dio.delete(path, queryParameters: parameters);
  }

  void setHeaders(String token) {
    _dio.options.headers["token"] = token;
  }
}
